import base64
import json
import os
import os.path as osp

import cv2
import numpy as np
import PIL.Image
from labelme import utils
import math

'''
我使用的labelme版本是3.16.7，建议使用该版本的labelme，有些版本的labelme会发生错误
此处生成的标签图是8位彩色图，每个像素点的值就是这个像素点所属的种类
'''

#2022.3.20 增加新功能 是得标签覆盖顺序是 先覆盖大块，再覆盖小块； 该功能测试成功

if __name__ == '__main__':
    root=r"F:\HIKRobot_data\data_process\训练数据\data1"
    jpgs_path   = root+"\JPEGImages"


    pngs_path   = root+"\SegmentationClass"
    if not os.path.exists(jpgs_path):
        os.makedirs(jpgs_path)

    if not os.path.exists(pngs_path):
        os.makedirs(pngs_path)

    #classes     = ["_background_",'mortar', 'qinghui_stone', 'yellow_stone', 'moorstone', 'basalt']
    classes     = ["_background_",'ni', 'aggregate', 'clean_aggregate']
    # classes     = ["_background_","cat","dog"]
    
    count = os.listdir(root)
    for i in range(0, len(count)):
        path = os.path.join(root, count[i])

        if os.path.isfile(path) and path.endswith('json'):
            data = json.load(open(path))
            
            if data['imageData']:
                imageData = data['imageData']
            else:
                imagePath = os.path.join(os.path.dirname(path), data['imagePath'])
                if not os.path.isfile(imagePath):
                    continue
                #需要json 里面要有imageData 部分
                with open(imagePath, 'rb') as f:
                    imageData = f.read()
                    imageData = base64.b64encode(imageData).decode('utf-8')

            img = utils.img_b64_to_arr(imageData)
            label_name_to_value = {'_background_': 0}
            for shape in data['shapes']:
                label_name = shape['label']
                if label_name in label_name_to_value:
                    label_value = label_name_to_value[label_name]
                else:
                    label_value = len(label_name_to_value)
                    label_name_to_value[label_name] = label_value
            
            # label_values must be dense
            label_values, label_names = [], []
            for ln, lv in sorted(label_name_to_value.items(), key=lambda x: x[1]):
                label_values.append(lv)
                label_names.append(ln)
            assert label_values == list(range(len(label_values)))

            shapes=data['shapes']

            #opencv 只接受cv_32f 等 的数据类型
            shapes = sorted(shapes, key=lambda
                shape:cv2.contourArea(np.array(shape['points'],dtype=np.float32)), reverse=True)

            lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)

            PIL.Image.fromarray(img).save(osp.join(jpgs_path, count[i].split(".")[0]+'.jpg'))

            new = np.zeros([np.shape(img)[0],np.shape(img)[1]])
            for name in label_names:
                index_json = label_names.index(name)
                index_all = classes.index(name)
                new = new + index_all*(np.array(lbl) == index_json)

            utils.lblsave(osp.join(pngs_path, count[i].split(".")[0]+'.png'), new)
            print('Saved ' + count[i].split(".")[0] + '.jpg and ' + count[i].split(".")[0] + '.png')
